package com.changyou.kf.common.util;

import com.fasterxml.uuid.EthernetAddress;
import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.impl.TimeBasedGenerator;
import org.apache.commons.lang3.RandomStringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * UuidGenerator.
 *
 * @author wujun
 * @since 2017/07/31
 */
public class UuidGeneratorUtils {

    private static TimeBasedGenerator timeBasedGenerator;

    /** 122192928000000000 */
    private static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L;

    static {
        timeBasedGenerator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
    }

    public static String getNextId() {
        return timeBasedGenerator.generate().toString();
    }

    public static long getLongNextId() {
        return timeBasedGenerator.generate().timestamp();
    }

    public static String getShortNextId() {
        return timeBasedGenerator.generate().toString().replace("-", "");
    }

    /**
     * Returns milis for timestamp of given uuid.
     *
     * @param uuid
     * @return
     */
    public static long getTimeFromUUID(UUID uuid) {
        return (uuid.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH) / 10000;
    }

    /**
     * Returns milis for timestamp of given uuid.
     *
     * @param uuid
     * @return
     */
    public static long getTimeFromUUID(long uuid) {
        return (uuid - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH) / 10000;
    }

    /**
     * 生成随机文件名：当前年月日时分秒+五位随机数
     *
     * @return
     */
    public static String getRandomFileName() {
        LocalDateTime dateTime = LocalDateTime.now();
        String now = dateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        // 三位随机数，避免并发
        String rannum = RandomStringUtils.secure().nextNumeric(5);
        return  now.concat(rannum);
    }
}
